import { useEffect, useState } from 'react'
import { useUpdateEffect } from 'ahooks'
import { Button, Drawer, Form, Input, message, Popconfirm, Select, Space, Spin, theme } from 'antd'

import { SPIN_DELAY } from '@/components/Loading'
import { useAntdPopupAnimation } from '@/services/popupSlot'
import { useCustomerBoundStore } from '../CustomerInfo'
import { apiGetCusEmialTemplateInfo, apiSendEmailTemplate } from './apis'
import { Files, IFile } from './Files'
import { ICusEmailTemplateInfo } from './interface'
import { fileSizeTip, filesSizeTip, fileToBase64 } from './utils'
import styles from './styles.module.less'

interface ISendCusEmailDrawerProps {
  destroy: () => void
  onSuccess?: () => void
}

export const SendCusEmailDrawer = ({ destroy, onSuccess }: ISendCusEmailDrawerProps) => {
  const { open, onHide, afterOpenChange } = useAntdPopupAnimation(destroy)
  const { token } = theme.useToken()

  const associatesList = useCustomerBoundStore(v => v.data?.associatesList) || []
  const defaultEmail = associatesList[0]?.email || ''

  const [fetching, setFetching] = useState(false)
  const [sending, setSending] = useState(false)
  const [recipient, setRecipient] = useState(defaultEmail)
  const [data, setData] = useState<ICusEmailTemplateInfo | null>(null)
  const [title, setTitle] = useState('')
  const [description, setDescription] = useState('')
  const [files, setFiles] = useState<IFile[]>([])

  useUpdateEffect(() => {
    setRecipient(defaultEmail)
  }, [defaultEmail])

  // 初始化
  useEffect(() => {
    setFetching(true)
    apiGetCusEmialTemplateInfo()
      .then(res => setData(res))
      .finally(() => setFetching(false))
  }, [])

  return (
    <Drawer
      className={styles.box}
      title="发送自定义邮件"
      width={1000}
      open={open}
      onClose={onHide}
      afterOpenChange={afterOpenChange}
      footer={
        <div className={styles.footer}>
          <Space>
            <Button onClick={onHide}>取消</Button>
            <Popconfirm
              title="确认要发送吗？"
              onConfirm={async () => {
                if (!data) return
                const fn = async () => {
                  try {
                    setSending(true)
                    const attachments = await fileToBase64(files).catch(err => {
                      if (err instanceof Error) message.error(err.message)
                      throw err
                    })
                    await apiSendEmailTemplate({
                      templateId: data.templateId,
                      recipient,
                      subject: data.subject,
                      attachments,
                      dynamicFields: [
                        { key: 'Routing_Title', value: title },
                        { key: 'Routing_Description', value: description },
                      ],
                    })
                    message.success(`发送成功`)
                    onSuccess?.()
                    onHide()
                  } finally {
                    setSending(false)
                  }
                }
                fn()
              }}
            >
              <Button
                type="primary"
                disabled={!data || !recipient || !title?.trim() || !description.trim()}
                loading={sending}
              >
                发送
              </Button>
            </Popconfirm>
          </Space>
        </div>
      }
    >
      <Spin spinning={fetching} delay={SPIN_DELAY}>
        {import.meta.env.VITE_APP_ENV !== 'prod' && (
          <Form.Item
            layout="vertical"
            label={
              <>
                客户邮箱
                <span style={{ fontWeight: 'normal', color: token.colorTextPlaceholder }}>
                  （测试用途，生产环境不会出现）
                </span>
              </>
            }
            required
          >
            <Input
              style={{ width: 400 }}
              placeholder="请输入客户邮箱"
              allowClear
              disabled={!data || sending}
              value={recipient}
              onChange={e => setRecipient(e.target.value)}
            />
          </Form.Item>
        )}
        <Form.Item layout="vertical" label="客户邮箱" required>
          <Select
            style={{ width: 400 }}
            placeholder="请选择客户邮箱"
            disabled={!data || sending}
            options={associatesList.map(d => ({
              label: [d.name, d.phone].filter(Boolean).join(' - '),
              value: d.email,
            }))}
            value={recipient || null}
            onChange={e => setRecipient(e)}
          />
        </Form.Item>
        <Form.Item layout="vertical" label="标题" required>
          <Input
            disabled={!data || sending}
            placeholder="请输入标题"
            value={title}
            onChange={e => setTitle(e.target.value)}
            onBlur={e => setTitle(e.target.value.trim())}
          />
        </Form.Item>
        <Form.Item layout="vertical" label="正文" required>
          <Input.TextArea
            placeholder="请输入正文"
            disabled={!data || sending}
            rows={6}
            value={description}
            onChange={e => setDescription(e.target.value)}
            onBlur={e => setDescription(e.target.value.trim())}
          />
        </Form.Item>
        <Form.Item
          layout="vertical"
          label={
            <>
              附件
              <span style={{ fontWeight: 'normal', color: token.colorTextPlaceholder }}>
                （{fileSizeTip}，{filesSizeTip}）
              </span>
            </>
          }
        >
          <Files disabled={!data || sending} files={files} onFilesChange={files => setFiles(files)} />
        </Form.Item>
      </Spin>
    </Drawer>
  )
}
